package com.jiashihui.schema_lgorithm.java.socket;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SocketClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(SocketClient.class);

    public static void main(String[] args) {
//        try {
//            sendBySocket("{\"lineCode\":\"shenzhonggongpei\"}", "127.0.0.1", 1990);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        // 剔除
//        try {
//            sendBySocket("{\"lineCode\":\"shenzhonggongpei\",\"datas\":[\"768123457449\"]}", "127.0.0.1", 1990);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        // 根据分拣线查询物流公司
        try {
            //String message = "{\"userName\":\"super\",\"pwd\":\"123456\",\"deviceType\":\"PDA\",\"deviceCode\":\"\",\"lineCode\":\"\"}";
            String message = "{\"packageCode\":\"1234567890123456789\",\"chuteCode\":\"23\",\"lineCode\":\"shenzhonggongpei\",\"deviceId\":\"1011\",\"opUserId\":\"101\",\"opUserName\": \"PDA\",\"createTime\": \"2019-10-25 00:02:25\",\"logisticsType\": \"ZT\"}";
            //String message = "{\"heartbeat\":\"hb_request\"}";
            //sendBySocket(message, "192.168.188.111", 1990);
            sendBySocket(message, "127.0.0.1", 1990);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 采用socket连接向服务器发送消息，接受响应信息 注意，如果是通过不同的ip port确定调用接口 这个方法要重写，将ip
     * port作为请求条件,现改为传固有参数进来
     *
     * @param text
     * @throws Exception
     */
    public static String sendBySocket(String text, String ip, int port) throws Exception {
        LOGGER.info("开始建立socket连接");
        Socket socket = new Socket(ip, port);
        InputStream is = socket.getInputStream();
        //InputStreamReader isr = new InputStreamReader(is, "UTF-8");
        // 2.获取客户端输出流
        OutputStream dos = socket.getOutputStream();
        LOGGER.info("连上服务端");
        // 3.向服务端发送消息
        ByteBuf buf = Unpooled.buffer(3);
        buf.writeInt(text.length() + 8);
        buf.writeInt(1760);
        buf.writeInt(1760);
        buf.writeBytes(text.getBytes());
        dos.write(buf.array());
        socket.shutdownOutput();
        LOGGER.info("成功向服务器发送消息");
        // 4.获取输入流，并读取服务器端的响应信息
//        BufferedReader br = new BufferedReader(isr);
//        String returnInfo = br.readLine();
        byte bytes[] = new byte[1024];
        StringBuilder sb = new StringBuilder();
        int len;
        while ((len = is.read(bytes, 0, bytes.length)) != -1) {
            sb.append(new String(bytes, 0, len, "UTF-8"));
        }
        sb.delete(0, 12);
//            sr.setResponseData(sb.toString(), null);
//            sr.setDataType(SampleResult.TEXT);
//            sr.setSuccessful(true);
        LOGGER.info("服务器端返回数据为：{}", sb);
        // 4.关闭资源
        is.close();
        dos.close();
        socket.close();
        return sb.toString();
    }
}
